package com.example.aicloud.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.net.NetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.example.aicloud.utils.CaptchaNameUtil;
import com.example.aicloud.utils.MinioUtil;
import com.example.aicloud.utils.Result;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 验证码
 * @Author Mr.Tang
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Resource
    private MinioUtil minioUtil;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 获取验证码
     * @return
     */
    @RequestMapping("/getCaptcha")
    public Result getCaptcha(HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 地址
        String url = "";
        // 定义图形验证码的宽高
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40);
        // 这里由于请求地址字符串格式问题导致minio存储失败, 所以用md5加密
        String fileName = CaptchaNameUtil.getCaptchaName(request);
        try(InputStream inputStream = new ByteArrayInputStream(lineCaptcha.getImageBytes());) {
            url = minioUtil.upload(fileName, inputStream, "image/png");
            String code = lineCaptcha.getCode();    // 正确的验证码
            redisTemplate.opsForValue().set(fileName, code,60, TimeUnit.SECONDS);    // 验证码存入redis中
        }
        return Result.success(url);
    }


}
